package com.itheima.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionResolver {

    /**
     * 处理异常,指定处理哪一类异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> handlerException(Exception e) {
        //打印信息
        log.error(e.getMessage());
        e.printStackTrace();
        if (e.getMessage().contains("Duplicate entry")) {
            //账号王五重复了  已存在
            //获取异常信息
            String message = e.getMessage();

            String split[] = message.split("'");
            return R.error("账号" + split[1] + "已存在");

        }
        return R.error("未知错误");

    }

    /*@ExceptionHandler(Exception.class)
    public R handlerException(Exception e){
        e.printStackTrace();
        return R.error(e.getMessage());
    }*/


    @ExceptionHandler(CustomException.class)
    public R<String> handlerException(CustomException e) {
        //打印信息
        log.error(e.getMessage());
        e.printStackTrace();
        return R.error(e.getMessage());

    }
}
